package com.dorm.cj.join;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

public class ForkJoinMain {

    public static void main(String[] args) {
        SumTask sumTask = new SumTask(1L, 11L);
        Long res = ForkJoinPool.commonPool().invoke(sumTask);
        System.out.println(res);
    }

    static class SumTask extends RecursiveTask<Long> {

        Long start;
        Long end;

        public SumTask(Long start, Long end) {
            this.start = start;
            this.end = end;
        }

        @Override
        protected Long compute() {
            System.out.println("当前线程：------" + Thread.currentThread() + "start:" + start + " end:" + end);
            //求从start一直加到end的和
            //差值在100以内，单线程循环
            Long temp = 0L;
            if (this.end - this.start < 4) {
                for (Long i = this.start; i < end; i++) {
                    temp += i;
                }
                return temp;
            }

            long middle = (end + this.start) / 2;
            SumTask sumTask1 = new SumTask(this.start, middle);
            SumTask sumTask2 = new SumTask(middle, end);
            invokeAll(sumTask1, sumTask2);
            Long res1 = sumTask1.join();
            Long res2 = sumTask2.join();
            System.out.println("当前线程res：------" + Thread.currentThread() + (res1 + res2));

            return res1 + res2;
        }
    }
}
